import {Button, message} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {useIntl, history, SelectLang, Link} from 'umi';
import ProTable from '@ant-design/pro-table';
import {ProFormGroup, ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import ProForm from '@ant-design/pro-form'
import {generateSuffix, getPrefix, registerUser} from '@/services/doa/irs'
import {generateKey} from '@/services/doa/grs'

import ProCard from "@ant-design/pro-card";
import styles from "./index.less";
import Footer from "@/components/Footer";

const UserRegister = () => {


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const [suffixValue, setSuffixValue] = useState("suffix")
  const [prefixValue, setPrefixValue] = useState("prefix")
  const [submittedValue, setSubmittedValue] = useState({})
  const [keyValue, setKeyValue] = useState({})
  const [preview, setPreview] = useState([{}, {}, {}, {}, {}])
  const actionRef = useRef();


  const formRef = useRef()

  const info = (msg) => {
    message.info(msg);
  };

  //使用useEffect来解决setState状态信息更新不及时的问题
  useEffect(() => {
    updatePreview()
    actionRef.current.reloadAndRest()
  }, [submittedValue])

  useEffect(() => {
    getPrefix().then((res) => {
      if (res?.success) {
        setPrefixValue(res.data)
      }
    })
  }, [])

  const deses = {
    "doi": "用户标识",
    "organization": "组织机构",
    "publicKey": "公钥",
    "suffix": "标识后缀",
  }

  const updatePreview = () => {
    const data = []
    for (const key in submittedValue) {
      data.push({key: key, value: submittedValue[key], 'des': deses[key]})
    }
    setPreview(data)
  }

  const onGenerateKey = async () => {
    generateKey({doi: submittedValue?.doi}).then((data) => {
      setKeyValue(data.data);
      formRef?.current?.setFieldsValue({
        publicKey: data.data
      })
      const tmp = {...submittedValue}
      tmp.publicKey = data.data
      setSubmittedValue(tmp)
    })
  }

  const onGenerateSuffix = async () => {

    let prefixFromServer = ''
    await getPrefix().then((res) => {
      if (res?.success) {
        setPrefixValue(res.data)
        prefixFromServer = res.data
      }
    })

    generateSuffix({"type": "dou"}).then((data) => {
      setSuffixValue(data.data);

      formRef?.current?.setFieldsValue({
        suffix: data.data
      })

      const tmp = {...submittedValue}
      tmp.suffix = data.data
      tmp.doi = prefixFromServer + '/' + data.data

      setSubmittedValue(tmp)
    })
  }
  const onValuesChanged = (values) => {
    console.log(values)
    setSuffixValue(values?.suffix)
    setSubmittedValue({...values, 'doi': prefixValue + '/' + suffixValue})
  }

  const onSubmit = () => {
    registerUser(submittedValue).then((response) => {
      if (response?.success == true) {
        info('用户注册！')
        history.push('/user/login');
      }
    })
  }

  const columns = [
    {
      dataIndex: 'key',
      title: '键',
    },
    {
      dataIndex: 'value',
      title: '值',
    },
    {
      dataIndex: 'des',
      title: '描述',
    }
  ];

  return (

    <div className={styles.container}>
      <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang/>}
      </div>
      <div className={styles.content}>
        <div className={styles.top}>
          <div className={styles.header}>
            <Link to="/">
              {/*<img alt="logo" className={styles.logo} src="/logo-1.png" />*/}
              <span className={styles.title}>数字对象标识管理系统</span>
            </Link>
          </div>
          <div className={styles.desc}>
            {intl.formatMessage({
              id: 'pages.user.register',
            })}
          </div>
        </div>

        <div className={styles.main}>
          <ProCard colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
            <ProForm
              formRef={formRef}
              onValuesChange={(_, values) => {
                onValuesChanged(values);
              }}
              submitter={{
                searchConfig: {
                  submitText: intl.formatMessage({
                    id: 'pages.user.register',
                    defaultMessage: '   注册',
                  }),
                },
              }}
              onFinish={async (values) => {
                onSubmit()
                console.log(values);
              }}
            >
              <ProFormText width="md" placeholder="请输入组织机构名称" name="organization"
                           rules={[
                             {
                               required: true,
                             }]}/>
              <ProFormGroup>
                <ProFormText width="md" placeholder="请输入后缀" name="suffix"
                             rules={[
                               {
                                 required: true,
                               }]}/>
                <Button type="primary" onClick={onGenerateSuffix}>自动生成</Button>
              </ProFormGroup>
              <ProFormGroup>
                <ProFormTextArea width="md" autoSize={true} placeholder="导入JWK格式的公钥" name="publicKey"
                                 rules={[
                                   {
                                     required: true,
                                   }]}/>
                <Button type="primary" onClick={onGenerateKey}>自动生成</Button>
              </ProFormGroup>
            </ProForm>
          </ProCard>
          <ProCard colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
            <h3>注册用户信息预览</h3>
            <ProTable
              columns={columns}
              request={(params, sorter, filter) => {
                return Promise.resolve({
                  data: preview,
                  success: true,
                });
              }}
              actionRef={actionRef}
              rowKey="preview"
              pagination={
                false
              }
              options={false}
              toolBarRender={false}
              search={false}
            />
          </ProCard>
        </div>
      </div>
      <Footer/>
    </div>
  );
};

export default UserRegister;
